import psutil
import time
import datetime

"""
2018.10.26
预计简化程序，
    简化字符串形式，"i min [rate][use_in_a_min][use_all_min]"
    简化open_write的调用，组织好字符串后统一写入文件
    简化程序结构，重构函数主体
2019-10-16 -> 已经不知道都写的啥了。 注释很重要啊！
"""
f_Log = './Log_test.txt'


def network_speed():
    """import psutil，time
    Network speed. Unit = ** Kb/s"""
    sent_a = psutil.net_io_counters().bytes_sent  # 获取某一时间点的数据量 -.发送的-
    recv_a = psutil.net_io_counters().bytes_recv  # 获取某一时间点的数据量 -.接受的-
    time.sleep(1)
    sent_b = psutil.net_io_counters().bytes_sent
    recv_b = psutil.net_io_counters().bytes_recv
    print(f"上行{round((sent_b-sent_a)/1024,2)}kb/s，下行{round((recv_b-recv_a)/1024,2)}kb/s")
    return recv_b - recv_a


def count_min(data_b=(0, 0), data_e=(0, 0)):
    """ data_b 开始数据  data_e 结束数据"""
    if data_e[0] == 0 or data_b[1] is 0: return 0, 0
    return round(((data_e[0] - data_b[0]) / (60 * 1024)), 2), round(((data_e[1] - data_b[1]) / (60 * 1024)), 2)


def network_amount_now() -> object:
    """Network amount. Unit = ** Kb; 得到当前时间的数据量"""
    _net = psutil.net_io_counters()
    return _net.bytes_sent, _net.bytes_recv


def network_minute():
    """
    计算60s内的网速，流量
    :return: str(up_rate, down_rate, up_use, down_use)
    """
    first = network_amount_now()
    time.sleep(60)
    last = network_amount_now()

    # round(一个浮点数, 保留浮点数的位数) 返回四舍五入的位数
    sent_use_level = round(((last[0] - first[0]) / (1024 * 1024)), 3)  # 计算这一分钟的使用量（单位：MB）
    recv_use_level = round(((last[1] - first[1]) / (1024 * 1024)), 3)
    sent_rate = round(((last[0] - first[0]) / (60 * 1024)), 2)        # 计算 1min 内 的平均速度 （单位：kb/s）
    recv_rate = round(((last[1] - first[1]) / (60 * 1024)), 2)
    result_rate = f"[up_rate：{sent_rate}kb/s down_rate：{recv_rate}kb/s]"
    result_use = f"[up_use:{sent_use_level}Mb down_use:{recv_use_level}Mb]"
    result = result_rate + result_use
    return result.ljust(76)


if __name__ == "__main__":
    # 初始化写入文件
    with open(f_Log, "a", encoding="utf-8") as log1:
        log1.write("*" * 15 + f"\t开始时间：{time.strftime('%Y-%m-%d  %H:%M:%S', time.localtime())}\t" + "*" * 15 + '\n')

    begin = network_amount_now()
    cycle = 1
    while True:
        # 每分钟写入一次网速
        _str = f'{cycle}min\t[{datetime.datetime.now().strftime("%H:%M")}]'
        _str += network_minute()  # network_minute() 返回字符串
        counter = count_min(begin, network_amount_now())
        _str += f"累计上行数据:{counter[0]}Mb({round(counter[0]/(1024*8),4)}Gb)\t".ljust(26)
        _str += f"下行数据：{round(counter[1], 4)}Mb({round(counter[1]/(1024*8),4)}Gb)\n".ljust(26)
        open("./Log_test.txt", "a", encoding="utf-8").write(_str)
        cycle += 1
